package vip.xiaonuo.vein.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceChangeTypeEnum;
import vip.xiaonuo.facedoor.modular.device.listener.DevicePublisher;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceSourceEnum;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class PalmVeinStatusTask implements TimerTaskRunner {

    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private DevicePublisher publisher;


    @Override
    public void action(String jobParams,String taskId) {
        this.listeningStatus();
    }



    @Override
    @XxlJob("PalmVeinStatusTask")
    public void executeXxlJob() throws InterruptedException {
        this.listeningStatus();
    }

    private void listeningStatus() {
        List<DeviceBase> devices = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>()
                .eq(DeviceBase :: getDeviceType, DeviceCategory.SUB_TYPE_PALM)
                .eq(DeviceBase :: getDeviceState , "1"));

        Long rangeTime = 120 * 1000L;
        Long current = System.currentTimeMillis();

        for(DeviceBase device : devices){
            Long lastTime = device.getLastOnlineTime().getTime();
            if (current - lastTime > rangeTime){
                device.setDeviceState("2");
                deviceBaseService.saveOrUpdate(device);
                publisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.BASE, device);
            }
        }
    }
}
